import '../Scss/FormList.scss'
import { Result, Button, message, Table, Tree, InputNumber, Select, DatePicker, List } from 'antd'
import { useBoolean, useEventEmitter, useRequest } from 'ahooks'
import { FormAssembly } from '../../Form/FormAssembly'
import { Http } from '../../Api'
import { useEffect, useState, useCallback } from 'react'
import { Scenes, ProjectRegionTree } from '../../Router/MenuNav/Common/Conversion'
import { commonTableList, BuiltInData } from '../../Router/MenuNav/Common/common'
import { ModalBox } from '../ModalBox'
import dayjs from 'dayjs'

// 新增
export const Add = ({ data, actionRef, Off, configure, reloadEvent }) => {
    return <FormAssembly {...data} Off={Off} actionRef={actionRef} configure={configure} reloadEvent={reloadEvent} />
}

// 修改
export const Mod = ({ data, actionRef, Off, configure, reloadEvent }) => {
    return <FormAssembly {...data} Off={Off} actionRef={actionRef} configure={configure} reloadEvent={reloadEvent} />
}

// 删除
export const Del = ({ data, actionRef, Off, reloadEvent }) => {
    const [loading, { setTrue, setFalse }] = useBoolean(false)
    const { url, uuid, way } = data
    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: () => {
            if (!!actionRef) actionRef.current.reload()
            else reloadEvent.emit()
            Off()
            setFalse()
        },
        onError: () => setFalse,
    })
    const DeleteFunction = () => {
        setTrue()
        if (way === 'post') runAsync({ url, path: uuid })
        else runAsync({ url: `del${url}`, path: typeof uuid === 'string' ? [uuid] : [...uuid] })
    }
    return (
        <Result
            status="warning"
            title="您即将删除这条数据信息,是否确认?"
            extra={[
                <Button loading={loading} size="large" type="primary" key="delete" danger onClick={DeleteFunction}>
                    删除数据
                </Button>,
                <Button type="link" key="close" onClick={Off}>
                    取消
                </Button>,
            ]}
        />
    )
}

// 子项目配置数据
const ProjectFormItemColumns = async data => {
    const select = {
        scene: await Scenes(),
        projectType: BuiltInData.projectType,
        roadLevel: BuiltInData.roadLevel,
        isRenew: BuiltInData.isRenew,
        feasibleStatus: BuiltInData.isYesText,
        isInherit: BuiltInData.isYesText,
        isCompleted: BuiltInData.isYesText,
        currentPeriod: BuiltInData.CurrentPeriod,
    }
    const treeSelect = { towns: await ProjectRegionTree() }
    const TypeList = {
        scene: 'select',
        projectType: 'select',
        roadLevel: 'select',
        isRenew: 'select',
        feasibleStatus: 'select',
        isInherit: 'select',
        isCompleted: 'select',
        currentPeriod: 'select',
        certApprovalDate: 'Date',
        feasibleDate: 'Date',
        planCompleteDate: 'Date',
        commencementDate: 'Date',
        towns: 'treeSelect',
        remark: 'textarea',
    }
    const columns = data.map(({ projectFormItemName, projectFormItemCode }) => {
        const valueType = TypeList[projectFormItemCode]
        let data = {
            title: projectFormItemName,
            dataIndex: projectFormItemCode,
            valueType: valueType || 'input',
        }
        if (valueType === 'select') data.valueEnum = select[projectFormItemCode]
        if (valueType === 'treeSelect')
            data.fieldProps = {
                options: treeSelect[projectFormItemCode],
                fieldNames: { label: 'tableName', value: 'uuid' },
            }
        return data
    })

    return columns
}

// 子项目数据配置
export const ProjectFormItemValue = ({ data, Off }) => {
    const [messageApi, contextHolder] = message.useMessage()
    const { uuid } = data.data.record
    const { Permission } = data.data
    const [configure, setConfigure] = useState()
    const [Data, setData] = useState({})
    const { runAsync: getValue } = useRequest(Http, {
        manual: true,
        onSuccess: async res => {
            setData(
                res.reduce((result, { value, projectFormItemCode }) => {
                    return { ...result, [projectFormItemCode]: value }
                }, {}),
            )
            setConfigure({ columns: await ProjectFormItemColumns(res) })
        },
    })

    const { runAsync: posValue } = useRequest(Http, { manual: true })

    const fromBackEvent = useEventEmitter()
    fromBackEvent.useSubscription(val => {
        posValue({ url: 'posProjectFormItemValueSyncObject', data: val, path: [uuid] }).then(() =>
            messageApi.success('修改成功'),
        )
    })

    useEffect(() => {
        getValue({ url: 'getProjectFormItemValueListWithValue', data: { OrganizationUuid: uuid } })
    }, [getValue, uuid])

    return (
        <div className="ProjectFormItemValue">
            {contextHolder}
            {configure && (
                <FormAssembly
                    data={Data}
                    configure={configure}
                    Off={Off}
                    Back={fromBackEvent}
                    NoSubmit={
                        Permission.findIndex(v => v.uuid === '001be0b8d-4513-49d8-bae1-4c2719985dd5') !== -1
                            ? true
                            : false
                    }
                />
            )}
        </div>
    )
}

// 添加月报附件
export const MonthReportAttachment = ({ data, Off, reloadEvent }) => {
    const { uuid } = data.data.record
    const [configure] = useState({
        uuid,
        pageSize: 10,
        params: { projectCompanyMonthReportUuid: uuid },
        initialValues: { projectCompanyMonthReportUuid: uuid },
        added: 'posProjectCompanyMonthReportAttachment',
        columns: [
            {
                dataIndex: 'projectCompanyMonthReportUuid',
                title: 'projectCompanyMonthReportUuid',
                valueType: 'hidden',
                hideInTable: true,
            },
            { ...commonTableList.tableName, title: '月报主题', rules: true },
            { ...commonTableList.sortId, rules: true },
            {
                dataIndex: 'attachmentUuid',
                title: '文件附件',
                valueType: 'upload',
                valueFile: [1, 2, 3, 4, 5],
                fileUrl: 'fileUrl',
                rules: true,
                hideInTable: true,
            },
            {
                dataIndex: 'fileUrl',
                title: '文件附件',
                valueType: 'hidden',
                hideInSearch: true,
                hideInTable: true,
                hideInAdded: true,
                hideInModify: true,
                width: 400,
            },
        ],
    })
    return <FormAssembly Off={Off} configure={configure} reloadEvent={reloadEvent} />
}

// 项目附件
export const CompanyAttachment = ({ data }) => {
    const { Permission, record } = data.data
    const { uuid, tableName } = record
    const [ListData, setListData] = useState([])
    const [OptionsCall, setOptionsCall] = useState()
    const { runAsync: getData } = useRequest(Http, {
        manual: true,
        onSuccess: res => setListData(res.list),
    })
    const columns = [
        {
            title: '月报名称',
            dataIndex: 'tableName',
        },
        {
            title: '操作',
            dataIndex: 'options',
            render: (_, e) => {
                return [
                    <Button key="one" type="link" onClick={() => See(e)}>
                        查看附件
                    </Button>,
                    <Button key="two" type="link" onClick={() => Del(e)} danger>
                        删除
                    </Button>,
                ]
            },
        },
    ]

    const getDataList = useCallback(() => {
        getData({ url: 'getProjectCompanyMonthReportAttachment', data: { ProjectCompanyMonthReportUuid: uuid } })
    }, [getData, uuid])

    useEffect(() => {
        getDataList()
    }, [getDataList])

    const reloadEvent = useEventEmitter()
    reloadEvent.useSubscription(() => getDataList())

    const Add = () =>
        setOptionsCall({ type: 'MonthReportAttachment', data: { title: `${tableName} 附件`, data: { record } } })
    const See = e =>
        setOptionsCall({ type: 'Annex', data: { url: e.attachment.fileUrl, title: '月报附件', width: '90vw' } })
    const Del = e =>
        setOptionsCall({
            type: 'Del',
            data: { url: 'ProjectCompanyMonthReportAttachment', title: '删除月报附件', uuid: [e.uuid] },
        })
    return (
        <div className="CompanyAttachment">
            {Permission.findIndex(v => v.uuid === '0f1f68ff-de4d-403b-861d-e6e291d3a959') !== -1 && (
                <Button type="primary" onClick={() => Add()}>
                    添加附件
                </Button>
            )}
            <Table columns={columns} dataSource={ListData} rowKey="uuid" size="small" />
            <ModalBox OptionsCall={OptionsCall} reloadEvent={reloadEvent} />
        </div>
    )
}

// 八达文件柜
const getTree = ['getBadaStatOrganizationPppListTree', 'getBadaStatOrganizationBuildListTree']
const APIAttr = ['OrganizationPppListAttachment', 'OrganizationBuildListAttachment']
const orgType = ['OrganizationPppListUuid', 'OrganizationBuildListUuid']
const typeFil = ['pppListUuid', 'buildListUuid']
const typePut = ['organizationPppListUuid', 'organizationBuildListUuid']
const AddPerm = [
    '050b8959-92e7-431e-90e6-6b471d9ab6f8',
    '0983943a-daf0-4c92-9fef-18ee06ba638c',
    'd0996bd9-f88b-41cc-a9b2-60f37f748d04',
]
const DelPerm = [
    '406152ab-03f6-4597-aa22-82b70325c33f',
    '49767e17-8d49-4bd6-9ffc-129969267cd7',
    'cd02dd28-d121-497d-9cba-3a12b3c8d080',
]

export const BaDaFilingCabinet = ({ data }) => {
    const { Permission, dataType, record } = data.data
    const organizationUuid = record.organizationUuid || record.uuid

    const [TreeData, setTreeData] = useState()
    const [OptionsCall, setOptionsCall] = useState()

    const { runAsync: getTreeApi } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            if (dataType === 0) {
                const list = res.pop()
                setTreeData([res, [list]])
            }
            if (dataType === 1) {
                let last = res.pop()
                res.splice(1, 0, last)
                setTreeData([res])
            }
        },
    })

    const getTreeFun = useCallback(() => {
        getTreeApi({ url: getTree[dataType], data: { organizationUuid: organizationUuid } })
    }, [dataType, getTreeApi, organizationUuid])

    useEffect(() => {
        getTreeFun()
    }, [getTreeFun])

    const reloadEvent = useEventEmitter()
    reloadEvent.useSubscription(() => getTreeFun())

    return (
        <div className="BaDaFilingCabinet">
            {TreeData && (
                <div className="TreeDataBox">
                    {TreeData.map((item, index) => (
                        <div key={index} className={index === 0 ? 'left' : 'right'}>
                            {item.map(({ uuid, tableName, children }) => (
                                <div key={uuid} className="List">
                                    <div className="Title">{tableName}</div>
                                    <div className="Content">
                                        {children.map(
                                            ({
                                                uuid,
                                                organizationBuildListUuid,
                                                organizationPppListUuid,
                                                tableName,
                                                isImportant,
                                                planAttachmentCount,
                                                completeAttachmentCount,
                                            }) => (
                                                <div
                                                    className="Item"
                                                    key={uuid}
                                                    style={planAttachmentCount === 0 ? { color: '#999999' } : {}}
                                                    onClick={() => {
                                                        if (planAttachmentCount === 0) return false
                                                        setOptionsCall({
                                                            type: 'BaDaFilingCabinetDetails',
                                                            data: {
                                                                title: `${tableName} 附件`,
                                                                data: {
                                                                    uuid,
                                                                    dataType,
                                                                    organizationPppListUuid,
                                                                    organizationBuildListUuid,
                                                                    planAttachmentCount,
                                                                    reloadEvent,
                                                                    Permission,
                                                                    organizationUuid,
                                                                },
                                                            },
                                                        })
                                                    }}
                                                >
                                                    {isImportant ? <div>【重要节点】</div> : ''}
                                                    <div>{tableName}</div>
                                                    {planAttachmentCount !== 0
                                                        ? `( ${completeAttachmentCount}/${planAttachmentCount} )`
                                                        : ''}
                                                </div>
                                            ),
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ))}
                </div>
            )}
            <ModalBox OptionsCall={OptionsCall} reloadEvent={reloadEvent} />
        </div>
    )
}

export const BaDaFilingCabinetForm = ({ data, Off, reloadEvent }) => {
    const { dataType, uuid, organizationUuid, record, attachmentUuid } = data.data
    const [configure] = useState({
        initialValues: {
            organizationUuid,
            [typeFil[dataType]]: uuid,
            [typePut[dataType]]: uuid,
            attachmentUuid: attachmentUuid,
        },
        added: `pos${APIAttr[dataType]}`,
        modify: `put${APIAttr[dataType]}`,
        columns: [
            commonTableList.uuid,
            {
                dataIndex: 'organizationUuid',
                title: 'organizationUuid',
                valueType: 'hidden',
                hideInTable: true,
            },
            {
                dataIndex: typeFil[dataType],
                title: typeFil[dataType],
                valueType: 'hidden',
                hideInTable: true,
            },
            {
                dataIndex: typePut[dataType],
                title: typePut[dataType],
                valueType: 'hidden',
                hideInTable: true,
            },
            {
                dataIndex: 'attachmentUuid',
                title: 'attachmentUuid',
                valueType: 'hidden',
                hideInTable: true,
                hideInAdded: true,
            },
            { ...commonTableList.tableName, title: '附件名称', rules: true },
            { ...commonTableList.sortId, rules: true },
            {
                dataIndex: 'attachmentUuid',
                title: '文件附件',
                valueType: 'upload',
                valueFile: [1, 2, 3, 4, 5],
                fileUrl: 'fileUrl',
                rules: true,
                hideInTable: true,
                hideInModify: true,
            },
            {
                dataIndex: 'fileUrl',
                title: '文件附件',
                valueType: 'hidden',
                hideInSearch: true,
                hideInTable: true,
                hideInAdded: true,
                hideInModify: true,
                width: 400,
            },
        ],
    })

    return <FormAssembly data={record} Off={Off} configure={configure} reloadEvent={reloadEvent} />
}

export const BaDaFilingCabinetDetails = ({ data }) => {
    const { title } = data
    const {
        uuid,
        dataType,
        organizationPppListUuid,
        organizationBuildListUuid,
        planAttachmentCount,
        reloadEvent,
        organizationUuid,
        Permission,
    } = data.data
    const AddRequired = Permission?.some(v => AddPerm.includes(v.uuid))
    const DelRequired = Permission?.some(v => DelPerm.includes(v.uuid))
    const columns = [
        {
            title: '附件名称',
            dataIndex: 'tableName',
        },
        {
            title: '排序',
            dataIndex: 'sortId',
        },
        {
            title: '创建用户',
            dataIndex: 'createUserName',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
        },
        {
            title: '操作',
            dataIndex: 'options',
            render: (_, e) => {
                return [
                    <Button key="one" type="link" onClick={() => See(e)}>
                        查看附件
                    </Button>,
                    <Button key="thr" type="link" onClick={() => Mod(e)}>
                        修改
                    </Button>,
                    DelRequired && (
                        <Button key="two" type="link" onClick={() => Del(e)} danger>
                            删除
                        </Button>
                    ),
                ]
            },
        },
    ]
    const [ListData, setListData] = useState([])
    const [OptionsCall, setOptionsCall] = useState()

    const { runAsync: getDataApi } = useRequest(Http, { manual: true })

    const getData = useCallback(() => {
        const dataField = [organizationPppListUuid, organizationBuildListUuid]
        getDataApi({
            url: `get${APIAttr[dataType]}`,
            data: { [orgType[dataType]]: dataField[dataType], OrderField: 'sortId@asc' },
        }).then(res => setListData(res.list))
    }, [dataType, getDataApi, organizationBuildListUuid, organizationPppListUuid])

    useEffect(() => {
        getData()
    }, [getData])

    const Add = () =>
        setOptionsCall({
            type: 'BaDaFilingCabinetForm',
            data: {
                title: `添加 ${title}`,
                data: { uuid, organizationUuid, dataType },
            },
        })

    const Mod = e =>
        setOptionsCall({
            type: 'BaDaFilingCabinetForm',
            data: { title, data: { dataType, record: e, attachmentUuid: e.attachmentUuid } },
        })

    const Del = e =>
        setOptionsCall({ type: 'Del', data: { url: APIAttr[dataType], title: '删除附件', uuid: [e.uuid] } })
    const See = e =>
        setOptionsCall({ type: 'Annex', data: { url: e.attachment.fileUrl, title: '附件信息', width: '90vw' } })

    reloadEvent.useSubscription(() => getData())
    return (
        <div className="BaDaFilingCabinetDetails">
            {planAttachmentCount !== ListData.length && AddRequired && (
                <Button type="primary" onClick={() => Add()}>
                    添加附件
                </Button>
            )}
            <Table columns={columns} dataSource={ListData} rowKey="uuid" size="small" />
            <ModalBox OptionsCall={OptionsCall} reloadEvent={reloadEvent} />
        </div>
    )
}

const getConTree = ['getPPPListTree', 'getBuildListTree']
const getConData = ['getOrganizationPppList', 'getOrganizationBuildList'] // organizationUuid
const posBatch = ['posOrganizationPppListBatch', 'posOrganizationBuildListBatch']
const conField = ['pppListUuid', 'buildListUuid']

// 八达文件柜配置
export const BaDaFilingCabinetConfiguration = ({ data }) => {
    const { dataType, record } = data.data
    const organizationUuid = record.organizationUuid || record.uuid
    const [messageApi, contextHolder] = message.useMessage()
    const [TreeData, setTreeData] = useState()
    const [CountNum, setCountNum] = useState()
    const { runAsync: getTree } = useRequest(Http, { manual: true })
    const { runAsync: getData } = useRequest(Http, { manual: true })
    const { runAsync: putData } = useRequest(Http, { manual: true })
    const getDataAPI = useCallback(() => {
        getData({ url: getConData[dataType], data: { organizationUuid } }).then(res => {
            setCountNum(
                res.list.map(item => ({
                    [conField[dataType]]: item[conField[dataType]],
                    planAttachmentCount: item.planAttachmentCount,
                })),
            )
        })
    }, [dataType, getData, organizationUuid])

    useEffect(() => {
        getTree({ url: getConTree[dataType] }).then(res => {
            setTreeData(res)
            getDataAPI()
        })
    }, [dataType, getDataAPI, getTree])

    const Submit = () => {
        putData({ url: posBatch[dataType], data: CountNum, path: [organizationUuid] }).then(() =>
            messageApi.success('数据保存成功'),
        )
    }

    return (
        <div className="BaDaFilingCabinetConfiguration">
            {contextHolder}
            {TreeData && (
                <Tree
                    fieldNames={{ title: 'tableName', key: 'uuid' }}
                    treeData={TreeData}
                    defaultExpandAll={true}
                    titleRender={e => {
                        const { uuid, tableName, lowLevel } = e
                        return (
                            <div>
                                {lowLevel === 0 ? (
                                    CountNum && (
                                        <div className="NumberInput">
                                            <div>{tableName}</div>
                                            <InputNumber
                                                min={0}
                                                onChange={e => {
                                                    CountNum.find(
                                                        v => v[conField[dataType]] === uuid,
                                                    ).planAttachmentCount = e
                                                    setCountNum([...CountNum])
                                                }}
                                                defaultValue={
                                                    CountNum.find(v => v[conField[dataType]] === uuid)
                                                        ?.planAttachmentCount || 0
                                                }
                                            />
                                        </div>
                                    )
                                ) : (
                                    <div> {tableName} </div>
                                )}
                            </div>
                        )
                    }}
                />
            )}
            <div className="Submit">
                <Button style={{ width: 200 }} type="primary" onClick={Submit}>
                    保存数据
                </Button>
            </div>
        </div>
    )
}

const PaymentItem = ['getProjectBuildingPaymentItem', 'getProjectOperationPaymentItem']
const PaymentInit = ['posProjectBuildingPaymentStatBatch', 'posProjectOperationPaymentStatsBatch']
const PaymentUuid = ['projectBuildingPaymentItemUuid', 'projectOperationPaymentItemUuid']
const PaymentType = ['projectBuildingPaymentType', 'projectOperationPaymentType']

export const BadaBatchAdd = ({ data, Off }) => {
    const { dataType, OrgList, actionRef } = data.data
    const [messageApi, contextHolder] = message.useMessage()

    const { runAsync: getItem } = useRequest(Http, { manual: true })
    const { runAsync: posItem } = useRequest(Http, { manual: true })

    const [ItemList, setItemList] = useState([])
    const [Options, setOptions] = useState([])
    const [OrgSelect, setOrgSelect] = useState()
    const [Date, setData] = useState(dayjs())

    useEffect(() => {
        setOptions(Object.keys(OrgList).map(item => ({ value: item, label: OrgList[item] })))
        getItem({ url: PaymentItem[dataType], data: { OrderField: 'code@asc' } }).then(res => {
            setItemList(
                res.list.map(item => ({
                    [PaymentUuid[dataType]]: item.uuid,
                    code: item.code,
                    remark: item.remark,
                    tableName: item.tableName,
                    amount: 0,
                    typeName: BuiltInData[PaymentType[dataType]][item[PaymentType[dataType]]],
                    actualDate: dayjs().format('YYYY-MM-DD'),
                })),
            )
        })
    }, [OrgList, dataType, getItem])

    const Submit = () => {
        if (!OrgSelect) {
            messageApi.error('请先选择项目')
            return false
        }
        let data = ItemList.filter(v => v.amount > 0)
        if (data.length === 0) {
            messageApi.error('请至少添加一项数据')
            return false
        }
        data.forEach(item => (item.actualDate = dayjs(Date).format('YYYY-MM-DD')))
        posItem({
            url: PaymentInit[dataType],
            data,
            path: [OrgSelect],
        }).then(() => {
            messageApi.success('数据添加成功!')
            actionRef.current.reload()
            Off()
        })
    }

    return (
        <div className="BadaBatchAdd">
            {contextHolder}
            <div className="Options">
                <Select
                    showSearch={true}
                    placeholder="请选择项目"
                    style={{ width: '100%', marginBottom: 8 }}
                    options={Options}
                    filterOption={(input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                    onChange={e => setOrgSelect(e)}
                />
                <DatePicker
                    style={{ width: '100%', marginBottom: 8 }}
                    value={Date}
                    placeholder="请选择时间"
                    onChange={setData}
                />
            </div>
            <div className="List">
                {ItemList.length === 0 ? (
                    <div>暂无清单数据</div>
                ) : (
                    <List
                        header={
                            <div className="Header">
                                <div>清单名称</div>
                                <div>
                                    <div>类型</div>
                                    <div>金额(万元)</div>
                                </div>
                            </div>
                        }
                        size="small"
                        bordered
                        dataSource={ItemList}
                        renderItem={item => (
                            <List.Item>
                                <div className="Title">{item.tableName}</div>
                                <div className="Type">{item.typeName}</div>
                                <div className="Input">
                                    <InputNumber
                                        value={item.amount}
                                        placeholder="请输入金额"
                                        onChange={e => {
                                            ItemList.find(
                                                v => v[PaymentUuid[dataType]] === item[PaymentUuid[dataType]],
                                            ).amount = e
                                            setItemList([...ItemList])
                                        }}
                                    />
                                </div>
                            </List.Item>
                        )}
                    />
                )}
            </div>
            <div className="Submit">
                <Button type="primary" onClick={Submit}>
                    提交数据
                </Button>
            </div>
        </div>
    )
}

export const YearMonthSelectModal = ({ data, Off }) => {
    const { subText, url } = data.data
    const [loading, setLoading] = useState(false)
    const [Date, setData] = useState()

    const { runAsync } = useRequest(Http, { manual: true, onSuccess: () => Off() })

    const Zero = e => {
        if (e >= 10) return e
        else return `0${e}`
    }

    const onChange = e => {
        const year = e.year()
        const month = e.month() + 1
        setData(`${year}-${Zero(month)}`)
    }

    const onSubmit = () => {
        if (!Date) return false
        setLoading(true)
        runAsync({ url, path: [Date] })
    }

    return (
        <div className="YearMonthSelectModal">
            <DatePicker style={{ width: '100%', marginBottom: 16 }} onChange={onChange} picker="month" />
            <Button style={{ width: 200 }} type="primary" onClick={onSubmit} loading={loading}>
                {subText}
            </Button>
        </div>
    )
}
